package com.yuyou.fn.crm.service.impl;

import com.github.wens.framework.service.impl.SuperServiceImpl;
import com.github.wens.mybatisplus.examples.Example;
import com.github.wens.mybatisplus.plugins.Page;
import com.github.wens.mybatisplus.toolkit.IdWorker;
import com.yuyou.fn.common.constant.SexEnum;
import com.yuyou.fn.common.exception.BusException;
import com.yuyou.fn.common.util.*;
import com.yuyou.fn.crm.constant.PriorityEnum;
import com.yuyou.fn.crm.entity.CrmDepartment;
import com.yuyou.fn.crm.entity.CustomerResource;
import com.yuyou.fn.crm.entity.FromCategory;
import com.yuyou.fn.crm.entity.MarketImport;
import com.yuyou.fn.crm.mapper.MarketImportMapper;
import com.yuyou.fn.crm.service.*;
import com.yuyou.fn.crm.vo.ImportCustomerResourceVo;
import com.yuyou.fn.crm.vo.MarketImportQueryVo;
import com.yuyou.fn.educational.entity.BaseGrade;
import com.yuyou.fn.educational.entity.Campus;
import com.yuyou.fn.educational.entity.Student;
import com.yuyou.fn.educational.service.IBaseGradeService;
import com.yuyou.fn.educational.service.ICampusService;
import com.yuyou.fn.educational.service.IStudentService;
import com.yuyou.fn.educational.vo.StudentSaveOrUpdateVo;
import com.yuyou.fn.platform.service.IAreaTeamService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 *
 * MarketImport 表数据服务层接口实现类
 *
 */
@Service
public class MarketImportServiceImpl extends SuperServiceImpl<MarketImportMapper, MarketImport,Long> implements IMarketImportService {

    @Resource
    private IBaseGradeService baseGradeService ;

    @Resource
    private IAreaTeamService areaTeamService;

    @Resource
    private IFromCategoryService fromCategoryService;

    @Resource
    private ICampusService campusService;

    @Resource
    private ICustomerResourceService customerResourceService;

    @Resource
    private IStudentService studentService;

    @Resource
    private ICrmDepartmentService crmDepartmentService;

    @Resource
    private IVisitMonitorService visitMonitorService;

    @Override
    @Transactional
    public void importCustomerResource(Long areaTeamId,Long departmentId, List<ImportCustomerResourceVo> importCustomerResourceVos, Principals.Principal principal) {

        if(importCustomerResourceVos.isEmpty()){
            return ;
        }

        Date date = TimeUtils.nowDate();

        List<CustomerResource> recordAlloCampus=new ArrayList<>();
        CrmDepartment crmDepartment=crmDepartmentService.findById(departmentId);
        List<BaseGrade> grades = baseGradeService.findAllFromCache();
        List<Campus> campuses = campusService.findCampusByAreaTeamId(areaTeamId);
        String areaTeamName  = areaTeamService.findTeamNameById(areaTeamId);
        Map<String,BaseGrade> gradeName2Grade = BeanUtils.toMap(grades,"gradeName");
        Map<String,Campus> campusName2Campus = BeanUtils.toMap(campuses,"campusName");

        List<CustomerResource> customerResources = new ArrayList<>(importCustomerResourceVos.size());

        for( int i = 0 ; i < importCustomerResourceVos.size() ;i++  ){
            ImportCustomerResourceVo importCustomerResourceVo = importCustomerResourceVos.get( i );
            CustomerResource customerResource = new CustomerResource();
            customerResource.setCustomerResourceId(IdWorker.getId());
            customerResource.setStudentName(importCustomerResourceVo.getStudentName());
            customerResource.setPhoneNo(importCustomerResourceVo.getPhoneNo());
            customerResource.setProjectName(importCustomerResourceVo.getProjectName());
            if(StringUtils.isNoneEmpty(importCustomerResourceVo.getProjectTime() ) ){
                customerResource.setProjectTime(TimeUtils.parse(importCustomerResourceVo.getProjectTime(),"yyyy-MM-dd"));
            }

            customerResource.setBigCategory(importCustomerResourceVo.getFromBigCategoryName());
            customerResource.setSmallCategory(importCustomerResourceVo.getFromSmallCategoryName());

            PriorityEnum priorityEnum = PriorityEnum.valueOf(importCustomerResourceVo.getPriority());
            customerResource.setPriority(priorityEnum.ordinal());
            customerResource.setSex(SexEnum.valueOf(StringUtils.defaultIfEmpty(importCustomerResourceVo.getSex(),"未设置")).ordinal());
            customerResource.setAreaTeamId(areaTeamId);
            customerResource.setDepartmentId(departmentId);
            customerResource.setDepartmentName(crmDepartment.getDepartmentName());
            customerResource.setAreaTeamName(areaTeamName);
            customerResource.setActivityRegSituationId(importCustomerResourceVo.getActivityRegSituationId());
            customerResource.setSignStatus(importCustomerResourceVo.getSignStatus());

            customerResource.setRemark(importCustomerResourceVo.getRemark());

            if(StringUtils.isNoneEmpty(importCustomerResourceVo.getCampusName())){
                Campus campus = campusName2Campus.get(importCustomerResourceVo.getCampusName());
                if(campus == null ){
                    throw new BusException("无匹配系统意向校区：" + importCustomerResourceVo.getCampusName());
                }
                customerResource.setCampusId(campus.getCampusId());
                customerResource.setCampusName(campus.getCampusName());
                customerResource.setAlloStatus(1);
                customerResource.setAlloOperatorId(0l);
                customerResource.setAlloOperatorName("系统");
                customerResource.setAlloCreateTime(TimeUtils.now());
                recordAlloCampus.add(customerResource);
            }else{
                customerResource.setAlloStatus(0);
            }

            if(StringUtils.isNoneEmpty(importCustomerResourceVo.getGradeName())){
                BaseGrade baseGrade = gradeName2Grade.get(importCustomerResourceVo.getGradeName());
                if( baseGrade == null ){
                    throw new BusException("无匹配系统年级：" + importCustomerResourceVo.getGradeName());
                }
                customerResource.setGradeId(baseGrade.getGradeId());
                customerResource.setGradeName(baseGrade.getGradeName());

            }

            boolean isExist = customerResourceService.exist(importCustomerResourceVo.getStudentName(),importCustomerResourceVo.getPhoneNo(),importCustomerResourceVo.getProjectName(),date );
            if(isExist){
                customerResource.setValidateStatus(2);
                customerResource.setValidateMsg("重复导入");
            }else{
                customerResource.setValidateStatus(1);
                customerResource.setValidateMsg("导入成功");
            }


            customerResource.setImportOperatorId(principal.id);
            customerResource.setImportOperatorName(principal.name);

            customerResource.setFollowStatus(0);
            customerResource.setVisitStatus(0);
            customerResource.setVisitTimes(0);
            customerResource.setCreateTime(TimeUtils.now());
            customerResource.setUpdateTime(TimeUtils.now());

            if (importCustomerResourceVo.getRecycleDays()!=null){
                customerResource.setRecycleTime(TimeUtils.changeDateByNum(new Date(),importCustomerResourceVo.getRecycleDays()));
            }
            customerResources.add(customerResource);
        }

        Long marketImportId = IdWorker.getId();
        MarketImport marketImport = new MarketImport();
        marketImport.setMarketImportId(marketImportId);
        marketImport.setAreaTeamId(areaTeamId);
        marketImport.setAreaTeamName(areaTeamName);
        marketImport.setAcceptAmount(0);
        marketImport.setImportAmount(customerResources.size());
        marketImport.setRejectAmount(0);
        marketImport.setImportOperatorId(principal.id);
        marketImport.setImportOperatorName(principal.name);
        marketImport.setCreateTime(TimeUtils.now());
        marketImport.setUpdateTime(TimeUtils.now());

        for(CustomerResource customerResource : customerResources ){
            customerResource.setMarketImportId(marketImportId);
            if(customerResource.getValidateStatus() == 1 ){
                marketImport.setAcceptAmount(marketImport.getAcceptAmount() + 1 );
            }else if(customerResource.getValidateStatus() == 2 ){
                marketImport.setRejectAmount(marketImport.getRejectAmount() + 1 );
            }
        }



        for(CustomerResource customerResource : customerResources){
            Student student = studentService.findByNameAndPhone(customerResource.getStudentName(), customerResource.getPhoneNo());
            if(student == null ){
                customerResource.setCustomerResourceType(1);

            }else {
                customerResource.setStudentId(student.getStudentId());
                customerResource.setCustomerResourceType(0);
            }

    /*        if(student != null ){
                customerResource.setCustomerResourceType(0);
                customerResource.setStudentId(student.getStudentId());
               // customerResourceService.updateCustomerResourceStudentId(customerResource.getCustomerResourceId(),student.getStudentId());
            }*/
        }
        insertSelective(marketImport);
        customerResourceService.insertBatch(customerResources);
        if (recordAlloCampus.size()>0){
            visitMonitorService.createVisitMonitor(recordAlloCampus);
        }

    }

    @Override
    public Page<MarketImport> findMarketImportByQuery(MarketImportQueryVo query, int pageNo, int pageSize) {
        if(query.getAreaTeamId() == null ){
            throw new IllegalArgumentException("Invalid areaTeamId");
        }

        if(query.getEndDate() != null ){
            query.setEndDate(DateUtils.addDays( query.getEndDate() ,1 ) );
        }

        Example<MarketImport> example = MarketImport.createExample();
        example.orderBy("createTime").desc();
        Example.Criteria criteria = example.createCriteria();
        CriteriaUtils.fillCondition(criteria,query);
        return findPageByExample(example,pageNo,pageSize);
    }

    @Override
    public List<CustomerResource> findImportDetailByMarketImportId(Long marketImportId) {
        return customerResourceService.findCustomerResourceByMarketImportId(marketImportId);
    }
}